import { onMounted, onUnmounted, ref, nextTick } from 'vue'

export const scrollContentId = 'content-scroll'

export function useMobileFooterFixed() {
  const isKeyboardVisible = ref(false)
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)
  const isAndroid = /Android/i.test(navigator.userAgent)

  const KEYBOARD_HEIGHT = 340 // iOS 常见键盘高度
  let savedScrollTop = 0
  let scrollHandler: ((e: Event) => void) | null = null
  let rafId: number | null = null

  const getScrollContainer = () => document.getElementById(scrollContentId)

  // Android：保存当前滚动位置
  const saveScroll = () => {
    if (!isAndroid) return
    const el = getScrollContainer()
    if (el) savedScrollTop = el.scrollTop
  }

  // 恢复滚动位置（用于 Android）
  const restoreScroll = () => {
    if (!isAndroid || savedScrollTop <= 0) return
    const el = getScrollContainer()
    if (el) el.scrollTop = savedScrollTop
  }

  // 阻止滚动偏移（Android）
  const preventScroll = (e: Event) => {
    if (savedScrollTop > 0) {
      e.preventDefault()
      restoreScroll()
    }
  }

  const handleIOSFocus = () => {
    isKeyboardVisible.value = true
    document.body.style.paddingBottom = `${KEYBOARD_HEIGHT}px`
    document.body.style.overflow = 'hidden'
    window.scrollTo(0, 0)
  }

  const handleIOSBlur = () => {
    isKeyboardVisible.value = false
    document.body.style.paddingBottom = ''
    document.body.style.overflow = ''
  }

  const handleAndroidFocus = () => {
    isKeyboardVisible.value = true
    saveScroll()

    const el = getScrollContainer()
    if (!el) return

    el.style.overflow = 'hidden'
    scrollHandler = preventScroll
    el.addEventListener('scroll', scrollHandler, { passive: false, capture: true })

    // 持续对齐滚动位置（防浏览器自动滚动）
    const align = () => {
      if (isKeyboardVisible.value && savedScrollTop > 0) {
        restoreScroll()
        rafId = requestAnimationFrame(align)
      }
    }
    rafId = requestAnimationFrame(align)
  }

  const handleAndroidBlur = () => {
    isKeyboardVisible.value = false

    // 延迟清理，防止浏览器后续自动滚动
    setTimeout(() => {
      const el = getScrollContainer()
      if (el && scrollHandler) {
        el.removeEventListener('scroll', scrollHandler, { capture: true })
        scrollHandler = null
        el.style.overflow = ''
      }
      if (rafId !== null) {
        cancelAnimationFrame(rafId)
        rafId = null
      }
      restoreScroll()
    }, 300)
  }

  const handleFocus = () => {
    if (isIOS) handleIOSFocus()
    else if (isAndroid) handleAndroidFocus()
  }

  const handleBlur = () => {
    if (isIOS) handleIOSBlur()
    else if (isAndroid) handleAndroidBlur()
  }

  // iOS 横竖屏时保持顶部
  const onResize = () => {
    if (isKeyboardVisible.value && isIOS) window.scrollTo(0, 0)
  }

  onMounted(() => {
    if (isIOS) window.addEventListener('resize', onResize)
  })

  onUnmounted(() => {
    if (isIOS) window.removeEventListener('resize', onResize)

    // 清理样式
    document.body.style.paddingBottom = ''
    document.body.style.overflow = ''

    // 清理 Android 监听
    if (isAndroid) {
      const el = getScrollContainer()
      if (el && scrollHandler) {
        el.removeEventListener('scroll', scrollHandler, { capture: true })
      }
      if (rafId !== null) cancelAnimationFrame(rafId)
    }
  })

  return {
    handleFocus,
    handleBlur,
    isKeyboardVisible
  }
}